<?php
namespace app\admin\controller;

use app\api\controller\KbxOrder;
use \think\Db;
use think\Exception;
use think\Request;
use think\Cookie;
use think\Cache;
use app\api\controller\KbxOther;
use app\api\controller\Esapi;
use app\api\model\GroupToursLine as GT;
use app\api\controller\Standard as SDController;
use app\api\model\Standard as SDModel;
use app\api\controller\Common as CommonApi;
use app\admin\controller\Product as ProController;
use app\admin\model\Standard as StandardModel;
use app\admin\model\Standardtags as StandardtagsModel;
use app\admin\model\Standardtrip as StandardtripModel;

class Standard extends User
{
    //列表
    public function index()
    {
        $post = $this->request->post();
        $temp_page=request()->param('page');//分页bug处理
        if(isset($temp_page)){
            //条件从缓存取出
            $post=Cookie::get('standardlist');
        }else{
            //把条件写入缓存
            Cookie::set('standardlist',$post);
        }
        if(!empty($post['name'])){
            $where['s.id|s.name|s.introduce'] = ['like','%'.$post['name'].'%'];
        }
        $city_function = '';
        if(isset($post['city_id']) && $post['city_id']!==""){
            $cityId = $post['city_id'];//用于搜索
            $city_function = function ($query) use ($cityId) {
                $query->where(function($query) use ($cityId){
                    $query->where(['st.startCityId'=>$cityId,'s.type'=>1]);
                })->whereOr(function($query) use ($cityId){
                    $query->where(['s.startCity'=>$cityId,'s.type'=>2]);
                });
            };
        }
        if(!empty($post['supplier_id'])){
            //获取管理员ID
            $supplier_admin_ids = (new SDController())->getSupplierAdminIds($post['supplier_id']);
            $where['s.supplier_admin_id'] = ['in',$supplier_admin_ids];
        }
        if(isset($post['status']) && $post['status']!==""){
            $where['s.status'] = $post['status'];
        }
        if(isset($post['topCate']) && $post['topCate']!==""){
            $where['s.topCate'] = $post['topCate'];
        }
        if(isset($post['tagid']) && $post['tagid']!==""){
            $tag_standard_ids = db('standardtags')->where('tagid',$post['tagid'])->column('sid');
            $where['s.id'] = ['in',$tag_standard_ids];
        }
        if(isset($post['show_toB']) && $post['show_toB']!==""){
            $where['s.show_toB'] = $post['show_toB'];
        }
        if(isset($post['auto_on_sale']) && $post['auto_on_sale']!==""){
            $where['s.auto_on_sale'] = $post['auto_on_sale'];
        }
        if(!empty($post['type'])){
            $where['s.type'] = $post['type'];
        }
        $where['is_deleted'] = 0;
        if(!empty($post['order_param'])){
            $order_desc = $post['order_param'];
        }else{
            $order_desc = 'is_recommend desc,sortNum desc,s.id desc';
        }
        $model = new StandardModel();
        $list = $model->alias("s")
            ->field("s.*,g.show,g.goods_tcode,g.orderType,g.goodssales,g.invented_sold,st.trip_id")
            ->join('goods g','g.goods_id=s.goods_id','left')
            ->join('standardtrip st','st.sid=s.id','left')
            ->where($where)
            ->where($city_function)
            ->order($order_desc)
            ->paginate(10);

        foreach ($list as $key=>$value){
            $list[$key]['real_sold'] = $value['goodssales'];
            $list[$key]['goodssales'] = $value['goodssales'] + $value['invented_sold'];
        }
        $this->assign("list",$list);
        $this->assign("wherelist",$post);
        $city = db("city")
            ->where("status",1)
            ->where("type","CITY")
            ->field("id,name,eng_name")
            ->select();
        $this->assign("cityList",$city);
        //供应商   不能放上面，引入类构造方法会过滤html标签
        list($supplier,$supplierNameArr) = (new ProController())->getAllSupplierList();
        $this->assign('supplierList',$supplier);

        //获取tob标签的类别
        $topCates = (new SDModel())->getStandardTopCates();
        $tagTypeIds = implode(',',array_column($topCates,'tagTypeIds'));
        $tags = db("tag")
            ->where(['tag_status'=>1])//未删除
            ->where(['tob_show'=>1])//tob 展示
            ->where(['tag_type'=>['in',$tagTypeIds]])
            ->order("tag_id asc")
            ->select();

        $this->assign("topCate",$topCates);
        $this->assign("tags",$tags);
        return $this->fetch();
    }

    //详情页
    public function detail(){
        $model = new StandardModel();
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if ($id > 0) {
            $info = $model->where('id', $id)->find();
            //正在使用的关联标签
            $tagsData = db("standardtags")
                ->alias("s")
                ->join("tag t","s.tagid=t.tag_id","left")
                ->where(['t.tag_status'=>1,'t.tob_show'=>1,"s.sid"=>$id])
                ->order("s.sort asc,s.id asc")
                ->select();

            $tripData = db("standardtrip strip")
                ->join("product p",'strip.trip_id=p.id','left')
                ->where("sid",$id)->find();
            if(!empty($tripData)){
                $tripData['from_address_arr'] = !empty($tripData['from_address_json']) ? json_decode($tripData['from_address_json'],true) : [];
                $tripData['to_address_arr'] = !empty($tripData['to_address_json']) ? json_decode($tripData['to_address_json'],true) : [];
            }

            if(!empty($tripData['trip_id']) && $tripData['trip_id']>0){
                $tripArr = db("product")->where("id",$tripData['trip_id'])->field("id,name")->find();
                $this->assign('tripArr', $tripArr);
            }
            //商品
            if(!empty($info['goods_id']) && $info['goods_id']>0){
                $goodsData = db("goods")->where("goods_id",$info['goods_id'])->field("goods_id,goods_name,orderType")->find();
                $goodsData['orderTypeTitle'] = !empty($goodsData['orderType'])?$this->getGoodsOrderType($goodsData['orderType']):"";
                $this->assign('goodsData', $goodsData);
            }
            //展示图
            if(!empty($info['image']) && $info['image']!==''){
                $infoDataImg = explode(",",$info['image']);
                $imageArr = !empty($infoDataImg) ? $infoDataImg : [];
                $this->assign('imageArr', $imageArr);
            }
            $this->assign('info', $info);
            $this->assign('tripData', $tripData);
            $this->assign('tagsData', $tagsData);
        }
        $city = db("city")
            ->where("status",1)
            ->where("type","CITY")
            ->field("id,name,eng_name")
            ->select();
        $this->assign("city",$city);
        //自定义标签
        //获取tob标签的类别
        $topCates = (new SDModel())->getStandardTopCates();
        $tagTypeIds = implode(',',array_column($topCates,'tagTypeIds'));
        $tags = db("tag")
            ->where(['tag_status'=>1])//未删除
            ->where(['tob_show'=>1])//tob 展示
            ->where(['tag_type'=>['in',$tagTypeIds]])
            ->order("tag_id asc")
            ->select();
//        foreach ($topCates as $key=>$value){
//            $topCates[$key]['subCates'] = [];
//            $tag_types = explode(',',$value['tagTypeIds']);
//            foreach ($tags as $tag_key=>$tag_value){
//                if(in_array($tag_value['tag_type'],$tag_types)){
//                    $topCates[$key]['subCates'][] = $tag_value;
//                    unset($tags[$tag_key]);
//                }
//            }
//        }
        $this->assign("tags",$tags);
        return $this->fetch();
    }

    //1、提交标品名称
    public function submitTitle(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $product_id = $this->request->has('product_id') ? $this->request->param('product_id', 0, 'intval') : 0;
        if ($this->request->isPost()) {
            $model = new StandardModel();
            if ($id > 0) {
                //是修改操作
                $post = $this->request->post();
                unset($post['id']);
                unset($post['product_id']);

                if ($model->allowField(true)->save($post, ['id' => $id])!==false) {
                    return $this->success('标品名称配置成功','',['id'=>$id]);
                } else {
                    return $this->error('标品名称配置失败');
                }
            } else {
                //是新增操作
                $post = $this->request->post();
                unset($post['id']);
                unset($post['product_id']);
                //判断是否需要新增标品
                $productInfo = db('product')->find($product_id);
                $standardType = 1;//默认时行程标品
                if(!empty($productInfo['item_num'])){
                    $goodsInfo = db('goods')->where('goods_tcode',$productInfo['item_num'])->find();
                    if(!empty($goodsInfo)){
                        $standard = db('standard')->where('goods_id',$goodsInfo['goods_id'])->find();
                        if(!empty($standard)){
                            $id = $standard['id'];
                        }else{
                            $standardType = $goodsInfo['orderType']=="Vehicle"?1:2;
                        }
                    }
                }
                if(empty($id)){
                    $post['type'] = $standardType;
                    $post['creattime'] = time();
                    $model->allowField(true)->save($post);
                    $id = $model->getLastInsID();
                }

                $standardtrip = db("standardtrip")->where("trip_id",$product_id)->find();
                if(empty($standardtrip)){
                    $gt_model = new GT();
                    $product = $gt_model->getTripData($product_id);
                    $lineSummary = $gt_model->getTripSummary($product);
                    $toursLineTitle = !empty($lineSummary) ? implode("\n",$lineSummary) : '';
                    $sTripData = [];
                    $sTripData['sid'] = $id;
                    $sTripData['trip_id'] = $product_id;
                    $sTripData['days'] = $product['days'];
                    $sTripData['startCityId'] = $product['start_city'];
                    $sTripData['toursLineTitle'] = $toursLineTitle;
                    db("standardtrip")->insert($sTripData);
                }
            }

            return $this->success('标品名称配置成功','',['id'=>$id]);
        }

    }

    //2、提交行程数据
    public function submitTripData(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if ($this->request->isPost()) {
            $model = new StandardtripModel();
            if ($id > 0) {
                //是修改操作
                $post = $this->request->post();
                $page_index = $post['page_index']??"";

                if(!empty($post['trip_id'])){
                    $product = db("product")->where(['id'=>$post['trip_id']])->find();
                    $standardInfo = db("standard")->where("id",$id)->find();
                    if(empty($standardInfo['goods_id'])) {
                        //获取行程关联的商品
                        $product_code = $product['item_num']??"";
                        if(!empty($product_code)){
                            $goods = db("goods")->field("goods_id,city_id")->where(['goods_tcode'=>$product_code])->find();
                            $goods_id = $goods['goods_id']??0;
                            if($goods_id>0){
                                db("standard")->where("id",$id)->update(['goods_id'=>$goods_id,'startCity'=>$goods['city_id']]);
                            }
                        }
                    }
                }else{
                    return $this->error("缺少产品ID");
                }
                unset($post['from_address']);
                unset($post['to_address']);
                unset($post['page_index']);
                $StandardtripData = $model->where("trip_id",$post['trip_id'])->find();
                if(!empty($StandardtripData)) {
                    unset($post['id']);
                    //检查产品的节点是否完整
                    $res = $this->checkProductHasChildren($StandardtripData['trip_id']);
                    if(!$res){
                        return $this->error('请完善产品信息，保证每天至少一个节点');
                    }

                    if ($model->allowField(true)->save($post, ['id' => $StandardtripData['id']])!==false) {
                        //如果不存在分段设置 则进行新建
                        if($StandardtripData['trip_id']!=$post['trip_id'] || empty($product['section_json'])){
                            $ProController = new ProController();
                            $ProController->createOneProductSection($post['trip_id']);
                        }
                        //刷新城市列表缓存
                        (new SDController())->refreshCityList();

                        if($page_index!=""){
                            db("standard")->where("id",$id)->update(['page_index'=>$page_index]);
                        }
                        if(!empty($post['endDays'])){
                            db("standard")->where("id",$id)->update(['s_endDays'=>$post['endDays']]);
                        }
                        return $this->success('产品信息配置成功');
                    } else {
                        return $this->error('产品信息配置失败');
                    }
                }else{
                    unset($post['id']);
                    $post['sid'] = $id;
                    $post['days'] = $product['days'];
                    if (false == $model->allowField(true)->insert($post)) {
                        return $this->error('产品信息配置失败');
                    } else {
                        $ProController = new ProController();
                        $ProController->createOneProductSection($post['trip_id']);

                        //刷新城市列表缓存
                        (new SDController())->refreshCityList();
                        return $this->success('产品信息配置成功');
                    }
                }
            } else {
                return $this->success('请补全标品名称');
            }
        }
    }

    //3、提交基础信息
    public function submitBasicData(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if ($this->request->isPost()) {
            $model = new StandardModel();
            $stmodel = new StandardtagsModel();
            if ($id > 0) {
                //是修改操作
                $post = $this->request->post();
                //$post['type'] = !empty($post['topCate'])&&$post['topCate']==1?1:2;//行程标品
                unset($post['id']);
                if ($model->allowField(true)->save($post, ['id' => $id])!==false) {
                    if(!empty($post['subCates'])){
                        foreach ($post['subCates'] as $key=>$value){
                            $insertData[] = [
                                'sid'=>$id,
                                'tagid'=>$value,
                                'sort'=>$key,
                                'creattime'=>time()
                            ];
                        }
                        $stmodel->allowField(true)->insertAll($insertData);
                    }

                    if(isset($post['s_endDays'])){
                        db("standardtrip")->where("sid",$id)->update(['endDays'=>$post['s_endDays']]);
                    }

                    $product = db("standardtrip")->where("sid",$id)->field("trip_id")->find();
                    $trip_id = $product['trip_id'];
                    return $this->success('基础信息配置成功','',['id'=>$trip_id]);
                } else {
                    return $this->error('基础信息配置失败');
                }
            } else {
                //是新增操作
                $post = $this->request->post();
                unset($post['id']);

                //$post['type'] = !empty($post['topCate'])&&$post['topCate']==1?1:2;//行程标品
                $post['creattime'] = time();
                if (false == $model->allowField(true)->save($post)) {
                    return $this->error('基础信息配置失败');
                } else {
                    $id = $model->getLastInsID();
                    if(!empty($post['subCates'])){
                        foreach ($post['subCates'] as $key=>$value){
                            $insertData[] = [
                                'sid'=>$id,
                                'tagid'=>$value,
                                'sort'=>$key,
                                'creattime'=>time()
                            ];
                        }
                        $stmodel->allowField(true)->insertAll($insertData);
                    }

                    $product = db("standardtrip")->where("sid",$id)->field("trip_id")->find();
                    $trip_id = $product['trip_id'];
                    return $this->success('基础信息配置成功','',['id'=>$trip_id]);
                }
            }
        }else{
            return $this->error('接口仅支持POST请求');
        }
    }

    //4、提交资源数据
    public function submitSourceData(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if ($this->request->isPost()) {
            $model = new StandardModel();
            if ($id > 0) {
                //是修改操作
                $post = $this->request->post();
                unset($post['id']);
                $goods_id = $post['goods_id']??0;
                if(!empty($goods_id)){
                    $goodsInfo = db('goods')->find($goods_id);
                    if(!empty($goodsInfo['orderType']) && $goodsInfo['orderType']=='Vehicle'){
                        $post['type'] = 1;//修改为行程标品
                    }
                }

                if ($model->allowField(true)->save($post, ['id' => $id])!==false) {
                    return $this->success('商品信息配置成功');
                } else {
                    return $this->error('商品信息配置失败');
                }
            } else {
                return $this->success('请补全标品名称');
            }
        }
    }

    //保存标签
    public function submitTagData(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if ($this->request->isPost()) {
            $model = new StandardtagsModel();
            if ($id > 0) {
                //是修改操作
                $post = $this->request->post();
                if(empty($post['subCates'])) return $this->error('请选择详细分类');
                //保存顶部分类
                db::startTrans();
                try{
//                    db("standard")->where(['id'=>$id])->update(['topCate'=>$post['topCate']]);
                    $model->where("sid",$id)->delete();
                    foreach ($post['subCates'] as $key=>$value){
                        $insertData[] = [
                            'sid'=>$id,
                            'tagid'=>$value,
                            'sort'=>$key,
                            'creattime'=>time()
                        ];
                    }
                    $model->allowField(true)->insertAll($insertData);
                    db::commit();
                    return $this->success('修改成功');
                }catch(Exception $e){
                    db::rollback();
                    return $this->error('修改失败，'.$e->getMessage());
                }
            } else {
                return $this->success('标品信息有误');
            }
        }else{
            return $this->error('请使用POST请求');
        }
    }

    //修改包车价格单位
    public function setCostCurrency()
    {
        $post = request()->post();
        if(!isset($post['sid']) || !isset($post['currency'])){
            $this->error('数据有误，请刷新后重试！');
        }else{
            $standard_id = $post['sid']??0;
            $currency = $post['currency']??"";

            $res = db("standardtrip")->where(['sid'=>$standard_id])->update(['costCurrency'=>$currency]);
            if($res){
                $this->success("更新成功,请检查派单价是否设置正确！");
            }else{
                $this->error("更新失败,请刷新后重试！");
            }
        }
    }

    //删除标品
    public function delete()
    {
        $post = request()->post();
        if(!isset($post['id']) || empty($post['id'])){
            $this->error("删除失败");
        }else{
            $res = db("standard")->where(['id'=>$post['id']])->update(['is_deleted'=>1]);
            if($res){
                $this->success("删除成功");
            }else{
                $this->error("删除失败");
            }
        }
    }

    //修改推荐状态
    public function changeRecommend()
    {
        $post = request()->post();
        if(!isset($post['id']) || !isset($post['is_recommend'])){
            $this->error("参数有误");exit;
        }
        $res = db("standard")->where(['id'=>$post['id']])->update(['is_recommend'=>$post['is_recommend']]);
        if($res!==false){
            //es 更新该商品
            $standard = db('standard')->find($post['id']);
            if(!empty($standard['show_toB'])){
                (new Esapi())->refreshStandardDataToES($post['id']);
            }
            $this->success("修改成功");
        }else{
            $this->error("修改失败");
        }
    }

    //修改权重排序
    public function changeSortNum()
    {
        $post = request()->post();
        if(!isset($post['id']) || !isset($post['sortNum'])){
            $this->error("参数有误");exit;
        }
        $res = db("standard")->where(['id'=>$post['id']])->update(['sortNum'=>$post['sortNum']]);
        if($res!==false){
            //es 更新该商品
            $standard = db('standard')->find($post['id']);
            if(!empty($standard['show_toB'])){
                (new Esapi())->refreshStandardDataToES($post['id']);
            }
            $this->success("修改成功");
        }else{
            $this->error("修改失败");
        }
    }

    //修改小程序加载模板
    public function changeAutoOnSale()
    {
        $post = request()->post();
        if(!isset($post['id']) || !isset($post['auto_on_sale'])){
            $this->error("参数有误");exit;
        }
        $res = db("standard")->where(['id'=>$post['id']])->update(['auto_on_sale'=>$post['auto_on_sale']]);
        if($res!==false){
            $this->success("修改成功");
        }else{
            $this->error("修改失败");
        }
    }
    //修改展示toB状态
    public function changeToB()
    {
        $post = request()->post();
        if(!isset($post['id']) || !isset($post['show_toB'])){
            $this->error("参数有误");exit;
        }

        $res = db("standard")->where(['id'=>$post['id']])->update(['show_toB'=>$post['show_toB']]);
        if($res!==false){
            //更新产品状态为未审核
            $info = db("standard")->find($post['id']);
            $standardtrip = db('standardtrip')->where('sid',$post['id'])->find();
            if($post['show_toB'] >0){
                if(!empty($standardtrip['trip_id'])){
                    $gt_model = new GT();
                    $product = $gt_model->getTripData($standardtrip['trip_id']);
                    $lineSummary = $gt_model->getTripSummary($product);
                    $toursLineTitle = !empty($lineSummary) ? implode("\n",$lineSummary) : '';
                    //行程路线
                    db('standardtrip')->where('trip_id',$standardtrip['trip_id'])->update([
                        'toursLineTitle'=>$toursLineTitle
                    ]);
                    //通过审核的状态
                    $refer = $post['refer'] ?? '';
                    if(empty($refer) || empty($info['allow_everyone_quote'])){
                        db('product')->where('id',$standardtrip['trip_id'])->update([
                            'check_status'=>2
                        ]);
                    }

                    $productInfo = db('product')->where('id',$standardtrip['trip_id'])->find();
                    if(!empty($productInfo['base_price_mode'])){
                        //基价模式更新产品的售价
                        (new ProController())->updateProductBasePriceSection($standardtrip['trip_id']);
                    }elseif(!empty($productInfo['new_price_flag'])){
                        //产品价格模式更新产品的售价
                        (new ProController())->updateProductPriceSection($standardtrip['trip_id']);
                    }
                }
                if($info['allow_everyone_quote'] > 0){
                    //es 更新该商品
                    (new Esapi())->refreshStandardDataToES($post['id']);
                    //通知相应供应商上架该商品
                    (new KbxOrder())->putOnSaleNotifyToKbx($post['id']);
                }

                //直接上架分销商小程序对应的产品
                $supplierAdminInfo = (new CommonApi())->getSupplierAdminInfo($info['supplier_admin_id']);
                if(!empty($supplierAdminInfo['company_id'])){
                    (new KbxOrder())->onSaleWxSoftSupplierStandard($post['id'],$supplierAdminInfo['company_id']);
                }

                $supplier_admin_name = $post['supplier_admin_name']??'';
                (new SDModel())->setOnSaleNoticeAtFirst($post['id'],$supplier_admin_name);
            }else{
                if(!empty($standardtrip['trip_id'])){
                    db('product')->where('id',$standardtrip['trip_id'])->update([
                        'check_status'=>0
                    ]);
                }
                //es 删除该商品
                (new Esapi())->delStandardDoc($post['id']);
                //通知相应供应商下架该商品
                (new KbxOrder())->pullOffShelvesNotifyToKbx($post['id']);
                //服务号通知供应商下架通知
                //(new KbxOrder())->sendProductOffAlertNotify($info);
            }
            if(!empty($post['type']) && $post['type']=='json'){
                return $this->result([],200,'修改成功',$post['type']);
            }else{
                $this->success("修改成功");
            }
        }else{
            $this->error("修改失败");
        }
    }

    //检查数据是否补全
    public function checkProInfo()
    {
        $post = request()->post();
        if(!isset($post['id'])){
            $this->error("参数有误");exit;
        }
        //检测是否符合上架标准
        $result['tips'] = [
            '关联行程' => 0,
            '关联商品' => 0,
            '商品套餐' => 0,
            '商品价格' => 0,
            '产品分类' => 0,
        ];
        $standard = db("standard s")
            ->field("s.*,st.trip_id")
            ->join("standardtrip st", 'st.sid=s.id', 'left')
            ->where(['s.id' => $post['id']])
            ->find();
        $result['goods_id'] = $standard['goods_id']??0;
        if (empty($standard)) {
            $this->error("修改失败", '', $result);
        } else {
            //行程标品
            if ($standard['type'] == 1) {
                if (empty($standard['trip_id'])) {
                    $this->error("请到编辑页面补全标品的行程信息", '', $result);
                } else {
                    $result['tips']['关联行程'] = 1;
                }
                if (empty($standard['goods_id'])) {
                    $this->error("请到编辑页面补全标品的商品信息", '', $result);
                } else {
                    $result['tips']['关联商品'] = 1;
                }
                //商品标品
            } else {
                $result['tips']['关联行程'] = 1;
                if (empty($standard['goods_id'])) {
                    $this->error("请到编辑页面补全标品的商品信息", '', $result);
                } else {
                    $result['tips']['关联商品'] = 1;
                }
            }

            //商品价格和套餐
            $goods = db("goods")->where("goods_id",$standard['goods_id'])->field("goods_tcode,code,`show`,standard_pro,source_id")->find();
            //viator 和 farehabor 跳过检测套餐和价格
            if(($goods['show']=2 && !empty($goods['code'])) || (!empty($goods['standard_pro']) && !empty($goods['source_id']))){
                $result['tips']['商品价格'] = 1;
                $result['tips']['商品套餐'] = 1;
            }elseif(!empty($goods['goods_tcode']) && $goods['goods_tcode']!==''){
                $product = db("product")->where("item_num",$goods['goods_tcode'])->field("id,new_price_flag,base_price_mode")->find();
                if(!empty($product) && $product['base_price_mode']==1){
                    //判断商品是否配置套餐和价格
                    $specData = db("product_base_package")->where(['product_id' => $product['id']])->find();
                    if (empty($specData)) {
                        $this->error("请先配置商品套餐", '', $result);
                    } else {
                        $result['tips']['商品套餐'] = 1;
                    }
                    $priceData = db("product_base_dailyprice")->where(['product_id' => $product['id']])->find();
                    if (empty($priceData)) {
                        $this->error("请先配置商品价格", '', $result);
                    } else {
                        $result['tips']['商品价格'] = 1;
                    }

                }elseif(!empty($product) && $product['new_price_flag']==1){
                    //判断商品是否配置套餐和价格
                    $specData = db("product_package")->where(['product_id' => $product['id']])->find();
                    if (empty($specData)) {
                        $this->error("请先配置商品套餐", '', $result);
                    } else {
                        $result['tips']['商品套餐'] = 1;
                    }
                    $priceData = db("product_dailyprice")->where(['product_id' => $product['id']])->find();
                    if (empty($priceData)) {
                        $this->error("请先配置商品价格", '', $result);
                    } else {
                        $result['tips']['商品价格'] = 1;
                    }

                }
            }else{
                //判断商品是否配置套餐和价格
                $specData = db("specs")->where(['goods_id' => $standard['goods_id']])->find();
                if (empty($specData)) {
                    $this->error("请先配置商品套餐", '', $result);
                } else {
                    $result['tips']['商品套餐'] = 1;
                }
                $priceData = db("personday")->where(['goods_id' => $standard['goods_id']])->find();
                if (empty($priceData)) {
                    $this->error("请先配置商品价格", '', $result);
                } else {
                    $result['tips']['商品价格'] = 1;
                }
            }

            //产品分类
            $cates = db("standardtags")->where('sid',$post['id'])->select();
            if(empty($cates)){
                $this->error("请到编辑页面补全标品的分类信息", '', $result);
            }else{
                $result['tips']['产品分类'] = 1;
            }

        }

        $this->success("成功", '', $result);
    }

    //获取标签列表
    public function showTagList(){
        $post = $this->request->post();
        $tagName = !empty($post['tagName']) ? $post['tagName'] : '';
        $tagType = !empty($post['tagType']) ? $post['tagType'] : '';
        $where = [];
        $where['tag_status'] = 1;
        $where['tag_type'] = $tagType;
        $where['tag_name'] = ['like', '%' . $tagName . '%'];
        $data = db("tag")
            ->where($where)
            ->order("tag_id desc")
            ->limit(20)
            ->select();

        return $data;
    }

    //获取商品列表
    public function showGoodsList(){
        $post = $this->request->post();
        $goods_name = !empty($post['GoodsName']) ? $post['GoodsName'] : '';
        $where = [];
        if($goods_name!==''){
            $where['goods_name|goods_tcode'] = ['like', '%' . $goods_name . '%'];
        }
        $data = db("goods")
            ->field("goods_id,goods_name,goods_tcode")
            ->where($where)
            ->order("goods_id desc")
            ->limit(20)
            ->select();
        return $data;
    }

    //获取行程列表
    public function showTripList(){
        $post = $this->request->post();
        $TripName = !empty($post['TripName']) ? $post['TripName'] : '';
        $where = [];
        if($TripName!==''){
            $where['name'] = ['like', '%' . $TripName . '%'];
        }
        //只有产品才能查询到
        $where['use_type'] = 1;
        //是否需要新增其他条件进行过滤
        // to be continued

        $data = db("product")
            ->field("id,name,start_city")
            ->where($where)
            ->order("id desc")
            ->limit(20)
            ->select();

        return $data;
    }

    //获取行程简介
    public function getTripSummary()
    {
        $post = request()->post();
        $trip_id = $post['trip_id']??0;
        $model = new GT();
        $trip = $model->getTripData($trip_id);
        $lineSummary = $model->getTripSummary($trip);
        $toursLineTitle = "";
        if(!empty($lineSummary)){
            $toursLineTitle = implode("\n",$lineSummary);
        }
        return $this->success("获取成功","",['title'=>$toursLineTitle,'city'=>$trip['start_city']]);
    }

    //配置房型
    public function roomconfig()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $info = db("standard")->find($id);
        if(empty($info)){
            $this->error("标品信息不存在");exit;
        }
        $configList = db("standard_hotel_config")->where(["link_id"=>$id])->order("sort_num asc")->select();
        $this->assign('configList',$configList);
        return $this->fetch();
    }

    //获取行程信息
    public function getTripData(){
        $post = $this->request->post();
        $tripid = !empty($post['tripid']) ? $post['tripid'] : 0;

        $res = [];
        if($tripid>0){
            $GroupToursLineModel = new GroupToursLineModel();
            $trip = $GroupToursLineModel->getTripData($tripid);
            $lineSummary = $GroupToursLineModel->getTripSummary($trip);

            $res['days'] = $trip['days'];
            $res['toursLineTitle'] = implode("\n",$lineSummary);
        }

        return $res;
    }

    public function productPricing()
    {
        $get = $this->request->get();
        $productid = !empty($get['id']) ? $get['id'] : 0;
        $carType = !empty($get['carType']) ? $get['carType'] : 1;
        $product = db('product')->find($productid);
        $transportData = $this->getOrderSystemTransportData($productid,$carType);
        //var_dump($transportData);exit;
        $totalPrice = 0;
        foreach ($transportData as $key=>$value){
            $totalPrice += $value['totalAmount'];
        }

        $carTypeList = [
            '1'=>'5座',
            '10'=>'7座',
            '15'=>'8座',
            '20'=>'12座',
            '30'=>'15座'
        ];
        $this->assign('product',$product);
        $this->assign('carType',$carType);
        $this->assign('carTypeList',$carTypeList);
        $this->assign('priceTable',$transportData);
        $this->assign('totalPrice',$totalPrice);
        return $this->fetch();
    }

    //交通核价接口封装
    //data是封装有active的schedule列表
    public function orderTransportApiData($id,$carType)
    {
        //$poiType = [1,4];//规定activeType去寻址poi
        //$airportType = [2,3];//规定activeType去寻址机场

        $resArr = [];
        $schedule = Db::name('pschedule')->where('groupid',$id)->order('displayorder')->select();
        if(!empty($schedule)){
            foreach ($schedule as $s_key=>$s_value){
                if(empty($s_value['transport_typeids'])){
                    $activities = [];
                }else{
                    $activities = [];
                    $active = Db::name('pactive')
                        ->alias('a')
                        ->join('city c','a.cityid=c.id','left')
                        ->join('poi p','a.poiid=p.id','left')
                        ->where('a.groupid',$s_value['id'])
                        ->field("a.*,c.kbx_id as cityId,c.lat,c.lng,p.lat as poi_lat,p.lng as poi_lng")
                        ->order('a.displayorder')->select();
                    if(empty($active)){
                        continue;
                    }
                    $trans_type_arr = explode(',',$s_value['transport_typeids']);
                    //sort($trans_type_arr);
                    $airportActive = [];
                    $airportActiveIndex = 0;

                    foreach ($trans_type_arr as $t_v){
                        $from = [];
                        $to = [];
                        $pois = [];
                        if($t_v==1){//交通 接机
                            foreach ($active as $a_k=>$a_v){
                                if($a_v['activeType']==2){//接机类型
                                    $airportActive = $a_v;
                                    $airportActiveIndex = $a_k;
                                    unset($active[$a_k]);
                                    break;
                                }
                            }
                            if(empty($airportActive)){
                                continue;
                            }
                            $from = [
                                'cityid'=>$airportActive['cityId'],
                                'placeId'=>$airportActive['poiid'],
                                'location'=>[
                                    'lat'=>$airportActive['airport_lat'],
                                    'lng'=>$airportActive['airport_lng'],
                                ],
                            ];
                            if(isset($active[$a_k+1]) && !empty($active[$a_k+1]['lat']) && !empty($active[$a_k+1]['lng'])){
                                $to = [
                                    'cityid'=>$airportActive['cityId'],
                                    'placeId'=>$airportActive['poiid'],
                                    'location'=>[
                                        'lat'=>$active[$a_k+1]['poi_lat'],
                                        'lng'=>$active[$a_k+1]['poi_lng'],
                                    ],
                                ];
                            }else{
                                $to = $from;
                            }
                        }elseif($t_v==2){//交通 送机
//                            $active = array_reverse($active);
                            foreach ($active as $a_k=>$a_v){
                                if($a_v['activeType']==3){//送机类型
                                    $airportActive = $a_v;
                                    $airportActiveIndex = $a_k;
                                    unset($active[$a_k]);
                                    break;
                                }
                            }
                            if(empty($airportActive)){
                                //还原数组
//                                $active = array_reverse($active);
                                continue;
                            }
                            $to = [
                                'cityid'=>$airportActive['cityId'],
                                'placeId'=>$airportActive['poiid'],
                                'location'=>[
                                    'lat'=>$airportActive['airport_lat'],
                                    'lng'=>$airportActive['airport_lng'],
                                ],
                            ];
                            if(isset($active[$a_k+1]) && !empty($active[$a_k+1]['lat']) && !empty($active[$a_k+1]['lng'])){
                                $from = [
                                    'cityid'=>$airportActive['cityId'],
                                    'placeId'=>$airportActive['poiid'],
                                    'location'=>[
                                        'lat'=>$active[$a_k+1]['poi_lat'],
                                        'lng'=>$active[$a_k+1]['poi_lng'],
                                    ],
                                ];
                            }else{
                                $from = $to;
                            }
                            //还原数组
                            //$active = array_reverse($active);
                        }
                        if(in_array($t_v,[1,2])){
                            if(empty($airportActive)){
                                continue;
                            }else{
                                $pois = [];
                                $activities[] = [
                                    'id'=>$airportActive['id'],
                                    'type'=>$this->getTransportType($t_v),
                                    'carType'=>$carType,
                                    'city'=>$airportActive['cityId'],
                                    'from'=>$from,
                                    'to'=>$to,
                                    'pois'=>$pois
                                ];
                                continue;
                            }
                        }
                        if(in_array($t_v,[3,4,5,6,8])){//交通类型 市内半日 市内一日 周边一日 长途
                            $validLatLng = [];
                            foreach ($active as $a_k=>$a_v){
                                //此类型包含 除其他以外的其他分类
                                //如果存在接送机 会通过以上步鄹移除机场poi
                                //若不存在接送机 机场poi也会计算到行程路线
                                if($a_v['activeType']!=6){
                                    //机场类型
                                    if(in_array($a_v['activeType'],[2,3]) && !empty($a_v['airport_lat']) && !empty($a_v['airport_lng'])){
                                        $a_v['lat'] = $a_v['airport_lat'];
                                        $a_v['lng'] = $a_v['airport_lng'];
                                        $validLatLng[] = $a_v;
                                    }elseif(!empty($a_v['poi_lat']) && !empty($a_v['poi_lat'])){
                                        $validLatLng[] = $a_v;
                                    }
                                }
                            }
                            if(empty($validLatLng)){
                                continue;
                            }else{
                                $start_poi = array_shift($validLatLng);
                                $from = [
                                    'cityid'=>$start_poi['cityId'],
                                    'location'=>[
                                        'lat'=>$start_poi['poi_lat'],
                                        'lng'=>$start_poi['poi_lng'],
                                    ],
                                ];
                                $pois = [];
                                if(count($validLatLng)>0){
                                    $end_poi = array_pop($validLatLng);
                                    $to = [
                                        'cityid'=>$end_poi['cityId'],
                                        'location'=>[
                                            'lat'=>$end_poi['poi_lat'],
                                            'lng'=>$end_poi['poi_lng'],
                                        ],
                                    ];
                                    if(count($validLatLng)>0){
                                        foreach ($validLatLng as $valid_k=>$valid_v){
                                            $pois[] = ['location'=>[
//                                                'title'=>$valid_v['poiname'],
                                                'lat'=>$valid_v['poi_lat'],
                                                'lng'=>$valid_v['poi_lng']
                                            ]];
                                        }
                                    }
                                }else{
                                    $to = $from;
                                }
                                $activities[] = [
                                    'id'=>$start_poi['id'],
                                    'type'=>$this->getTransportType($t_v),
                                    'carType'=>$carType,
                                    'city'=>$start_poi['cityId'],
                                    'from'=>$from,
                                    'to'=>$to,
                                    'pois'=>$pois
                                ];
                            }
                        }
                    }
                }
                $resArr[] = [
                    "id"=>$s_value['id'],
                    "fixed"=>$s_value['replace_director'],
                    "activities"=>$activities
                ];
            }
        }
        return $resArr;
    }

    //测试订单系统的包车核价
    public function getOrderSystemTransportData($id,$carType)
    {
        $post_data = $this->orderTransportApiData($id,$carType);
        //调用接口查询价格
        $KbxOther = new KbxOther();
        $priceData = $KbxOther->getCarPrice(['fullTravel'=>$post_data]);
//        var_dump($priceData);exit;
        $result = json_decode($priceData,true);
        //var_dump(json_encode(['fullTravel'=>$post_data]));exit;
        //var_dump($priceData);exit;
//        var_dump($result);exit;
        $data = [];
        //记录拥有司导返程的日期
        if(!empty($result)){
            foreach ($result as $key=>$value){
                $a_data = [];
                $hasReturn = false;
                if(!empty($value['activities'])){
                    foreach ($value['activities'] as $a_value){
                        $displayString = $a_value['displayString']??"";
                        $a_data[] = [
                            "hasReturn"=>false,//默认没有司导返程
                            "serviceType"=>$a_value['serviceType']??"",
                            "displayString"=>$displayString,
                            "totalAmount"=>$a_value['totalAmount']??0,
                            "distance"=>$a_value['distance']??0,
                            "duration"=>$a_value['duration']??0,
                            "extra"=>$a_value['extra']??[],
                        ];
                        if($displayString=='司导返程'){
                            $hasReturn = true;
                        }
                    }
                }
                if(!empty($a_data) && $hasReturn){
                    foreach ($a_data as $a_key=>$a_value){
                        $a_data[$a_key]['hasReturn'] = true;
                    }
                }
                $data[] = [
                    'id'=>$value['id'],
                    'displayString'=>$value['displayString']??'',
                    'totalAmount'=>$value['totalAmount']??0,
                    'detail'=>$a_data,
                    'hasReturn'=>$hasReturn,
                ];
            }
        }
        return $data;
    }

    //获取交通类型 （用于订单系统核价）
    public function getTransportType($type_id)
    {
        $data =  [
            "1"=>"Transport_Vehicle_FromAirport",
            "2"=>"Transport_Vehicle_ToAirport",
            "8"=>"Transport_Vehicle_ShortDistance",
            "3"=>"Transport_Vehicle_HalfDay",
            "4"=>"Transport_Vehicle_OneDay",
            "5"=>"Transport_Vehicle_Around",
            "6"=>"Transport_Vehicle_LongTrip",
            "7"=>"self",
        ];

        if(!empty($type_id)){
            return $data[$type_id];
        }else{
            return $data;
        }
    }

    public function checkpro()
    {
        return $this->fetch();
    }

    //add保存名称页面
    public function add(){
        $model = new StandardModel();
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        $product_id = $this->request->has('product_id') ? $this->request->param('product_id', 0, 'intval') : 0;
        $info = [];
        if ($id > 0) {
            $info = $model->where('id', $id)->find();
        }else{
            if($product_id>0){
                $sTrip = db('standardtrip')->where('trip_id',$product_id)->find();
                if(!empty($sTrip)){
                    $info = $info = $model->where('id', $sTrip['sid'])->find();
                }
                if(empty($info) || $info['name']==''){
                    $product = db("product")->where("id",$product_id)->field("name,item_num")->find();
                    $goods = db('goods')->where('goods_tcode',$product['item_num'])->find();
                    if(empty($product) || empty($goods)) return $this->error('请先增加产品对应的商品信息');
                    if(!empty($product['name']) && $product['name']!==''){
                        $product_name = $product['name'];
                        $this->assign('product_name', $product_name);
                        $this->assign('product_id', $product_id);
                    }
                }
            }
        }

        $this->assign('info', $info);

        return $this->fetch();
    }

    //行程数据页面
    public function process(){
        $model = new StandardModel();
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if ($id > 0) {
            $info = $model->where('id', $id)->find();
            $tripData = db("standardtrip strip")
                ->join("product p",'strip.trip_id=p.id','left')
                ->where("sid",$id)->find();
            if(!empty($tripData)){
                $tripData['from_address_arr'] = !empty($tripData['from_address_json']) ? json_decode($tripData['from_address_json'],true) : [];
                $tripData['to_address_arr'] = !empty($tripData['to_address_json']) ? json_decode($tripData['to_address_json'],true) : [];
            }

            if(!empty($tripData['trip_id']) && $tripData['trip_id']>0){
                $tripArr = db("product")->where("id",$tripData['trip_id'])->field("id,name")->find();
                $this->assign('tripArr', $tripArr);
            }

            $this->assign('info', $info);
            $this->assign('tripData', $tripData);
        }

        $city = db("city")
            ->where("status",1)
            ->where("type","CITY")
            ->field("id,name,eng_name")
            //->limit(20)
            ->select();
        $this->assign("city",$city);

        return $this->fetch();
    }

    //基础数据页面
    public function savebasic(){
        $model = new StandardModel();
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if ($id > 0) {
            $info = $model->where('id', $id)->find();
            //正在使用的关联标签
            $tagsData = db("standardtags")
                ->alias("s")
                ->join("tag t","s.tagid=t.tag_id","left")
                ->where(['t.tag_status'=>1,'t.tob_show'=>1,"s.sid"=>$id])
                ->order("s.sort asc,s.id asc")
                ->select();
            //商品
            if(!empty($info['goods_id']) && $info['goods_id']>0){
                $goodsData = db("goods")->where("goods_id",$info['goods_id'])->field("goods_id,goods_name")->find();
                $this->assign('goodsData', $goodsData);
            }

            $this->assign('info', $info);
            $this->assign('tagsData', $tagsData);
        }

        $city = db("city")
            ->where("status",1)
            ->where("type","CITY")
            ->field("id,name,eng_name")
            ->limit(20)
            ->select();
        $this->assign("city",$city);

        //自定义标签
        //获取tob标签的类别
        $topCates = (new SDModel())->getStandardTopCates();
        $tagTypeIds = implode(',',array_column($topCates,'tagTypeIds'));
        $tags = db("tag")
            ->where(['tag_status'=>1])//未删除
            ->where(['tob_show'=>1])//tob 展示
            ->where(['tag_type'=>['in',$tagTypeIds]])
            ->order("tag_id asc")
            ->select();
//        foreach ($topCates as $key=>$value){
//            $topCates[$key]['subCates'] = [];
//            $tag_types = explode(',',$value['tagTypeIds']);
//            foreach ($tags as $tag_key=>$tag_value){
//                if(in_array($tag_value['tag_type'],$tag_types)){
//                    $topCates[$key]['subCates'][] = $tag_value;
//                    unset($tags[$tag_key]);
//                }
//            }
//        }
        $this->assign("tags",$tags);
        return $this->fetch();
    }

    //商品数据页面
    public function savegoods(){
        $model = new StandardModel();
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if ($id > 0) {
            $info = $model->where('id', $id)->find();
            //商品
            if(!empty($info['goods_id']) && $info['goods_id']>0){
                $goodsData = db("goods")->where("goods_id",$info['goods_id'])->field("goods_id,goods_name")->find();
                $this->assign('goodsData', $goodsData);
            }

            $this->assign('info', $info);
        }

        return $this->fetch();
    }

    //修改流程进度页码
    public function submitPageIndex(){
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if ($this->request->isPost()) {
            $model = new StandardModel();
            if ($id > 0) {
                //是修改操作
                $post = $this->request->post();
                unset($post['id']);
                if ($model->allowField(true)->save($post, ['id' => $id])!==false) {
                    return $this->success('标品配置完成');
                } else {
                    return $this->error('流程结束flag设置失败');
                }
            } else {
                return $this->success('缺少id');
            }
        }
    }

    //检查产品是否每天都有节点
    public function checkProductHasChildren($trip_id)
    {
        $model = new GT();
        $trip = $model->getTripData($trip_id);
        if(empty($trip) || empty($trip['child'])){
            return false;
        }else{
            foreach ($trip['child'] as $key=>$value){
                if(count($value['child'])<1){
                    return false;
                }
            }
        }
        return true;
    }

    //获取商品的订单分类
    public function getGoodsOrderType($orderType="")
    {
        switch ($orderType){
            case "Ticket_FIT":
                return "地接社标品";
            case "Ticket_POI":
                return "门票类产品";
            case "Hotel":
                return "酒店";
            case "Custom":
                return "定制产品";
            case "Vehicle":
                return "用车";
            case "Ticket_AIR":
                return "机票";
            case "Rental_Device":
                return "物品购买/租赁";
            case "Other":
                return "其它";
                break;
            case "Price_Gap":
                return "补差价";
            case "Self_Drive":
                return "自驾游";
            case "Personal_Tailor":
                return "私人定制服务";
                break;
            case "Subscription":
                return "代订服务";
            default:
                return "";
        }
    }

    //同步资源标品的名称到标品名称
    public function updateStandardName()
    {
        $list = db('standard s')->field('s.id,s.name,g.goods_name')
            ->join('goods g','g.goods_id=s.goods_id','left')
            ->where('s.type = 2')
            ->having('name != goods_name')
            ->select();
        var_dump($list);
        if(!empty($list)){
            Db::startTrans();
            try{
                foreach ($list as $key=>$value){
                    db('standard')->where('id',$value['id'])->update(['name'=>$value['goods_name']]);
                }
                Db::commit();
                echo "更新成功";
            }catch(Exception $e){
                Db::rollback();
                echo "更新失败";
            }
        }
    }

}